package com.burst.reptile.framework.upload;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.redis.RedisCache;
import com.qcloud.cos.event.ProgressEvent;
import com.qcloud.cos.event.ProgressListener;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 腾讯云COS 文件上传监听
 * @author wujin
 *
 * @date: 2020年6月17日 下午11:35:16
 */
@Component
public class PutObjectProgressListener implements ProgressListener{
	
	@Autowired
	private RedisCache redisCache;
	
	/**
	 * 唯一标识
	 */
	private String uuid;
	
	/**
	 * 文件大小  字节
	 */
	private long size;
	
	@Override
	public void progressChanged(ProgressEvent progressEvent) {
		if(StrUtil.isNotEmpty(uuid)) {
			long bytesTransferred = progressEvent.getBytesTransferred();
			Object cacheObject = redisCache.getCacheObject(uuid);
			if(ToolUtil.isEmpty(cacheObject)) {
				if(size > 0 && bytesTransferred <= size) {
					BigDecimal mul = NumberUtil.mul(NumberUtil.div(new BigDecimal(bytesTransferred), new BigDecimal(size), 2), 100);
					String decimalFormat = NumberUtil.decimalFormat("#", mul);
					redisCache.setCacheObject(uuid + "_percentage", decimalFormat, 60, TimeUnit.MINUTES);
				}
				redisCache.setCacheObject(uuid, bytesTransferred, 60, TimeUnit.MINUTES);
			}else {
				if(NumberUtil.isLong(cacheObject.toString())) {
					long parseLong = NumberUtil.parseLong(cacheObject.toString());
					long total = bytesTransferred + parseLong;
					if(size > 0 && total <= size) {
						BigDecimal mul = NumberUtil.mul(NumberUtil.div(new BigDecimal(total), new BigDecimal(size), 2), 100);
						String decimalFormat = NumberUtil.decimalFormat("#", mul);
						redisCache.setCacheObject(uuid + "_percentage", decimalFormat, 60, TimeUnit.MINUTES);
					}else if(total > size){
						redisCache.setCacheObject(uuid + "_percentage", 100, 60, TimeUnit.MINUTES);
					}
					redisCache.setCacheObject(uuid, total, 60, TimeUnit.MINUTES);
				}
			}
		}
	}
	
	public String getUuid() {
		return uuid;
	}

	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	
	public long getSize() {
		return size;
	}

	public void setSize(long size) {
		this.size = size;
	}

}
